package lv.solcraft.replication.client.http;

import java.io.IOException;
import java.util.List;

import lv.solcraft.replication.common.OperDTO;
import lv.solcraft.replication.common.server.SendingFacade;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.Client;
import org.restlet.data.CharacterSet;
import org.restlet.data.Encoding;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.StringRepresentation;
import org.springframework.util.Assert;

import com.noelios.restlet.application.EncodeRepresentation;

public class HttpSendingFacade implements SendingFacade {

    private static final Logger log = Logger.getLogger(HttpSendingFacade.class);

    private String serverUrl;

    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public boolean storeOpers(String server, List<OperDTO> opers) {
        if (opers.isEmpty())
            return true;
        final int siteId = opers.get(0).getOperOwnerSiteId();
        JSONArray json = new JSONArray();
        for (OperDTO oper : opers) {
            JSONObject converted = OperConverter.convert(oper);
            json.add(converted);
        }
        try {
            makeRequest(server, json, siteId);
        } catch (IOException e) {
            throw new RuntimeException("Error while sending operations via HTTP POST", e);
        }
        return true;
    }

    private void makeRequest(String server, JSONArray opers, final int siteId) throws IOException {
        String urlString = serverUrl + "/" + server + "/send/" + siteId;
        if (log.isDebugEnabled()) {
            log.debug("Sending opers to " + urlString + ", " + opers);
        }
        Representation representation = new EncodeRepresentation(Encoding.GZIP, new StringRepresentation(opers
                .toString(), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8));
        Client client = HttpClientFactory.get();
        Response response = client.post(urlString, representation);
        try {
            Assert.isTrue(response.getStatus().isSuccess(), "Oper sending HTTP POST request failed, response code : "
                    + response.getStatus().getCode() + ", url " + urlString);
        } finally {
            response.release();
        }
    }
}
